package org.keshe.controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import org.keshe.CurrentUser;
import org.keshe.data.StuData;
import org.keshe.data.StuDataWithButton;
import org.keshe.user.AdminUser;

import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;

public class AdminStuManage implements Initializable {

    private AdminUser adminUser;

    @FXML
    private TableView<StuDataWithButton> table;

    @FXML
    private TextField inputSid;

    @FXML
    private TextField inputSname;

    @FXML
    private ChoiceBox<String> sexChoice;

    @FXML
    private TextField inputMajor;

    @FXML
    private TextField inputSearch;

    @FXML
    private TableColumn<StuDataWithButton, String> s_id;

    @FXML
    private TableColumn<StuDataWithButton, String> sname;

    @FXML
    private TableColumn<StuDataWithButton, String> sex;

    @FXML
    private TableColumn<StuDataWithButton, String> major;

    @FXML
    private TableColumn<StuDataWithButton, String> bedName;

    @FXML
    private TableColumn<StuDataWithButton, Button> buttonCol;

    private void loadTableContent(List<StuData> list){
        // 加入表中
        ObservableList<StuDataWithButton> observableList = FXCollections.observableArrayList();
        for(StuData stuData : list){
            observableList.add(new StuDataWithButton(stuData));
        }
        table.setItems(observableList);
        // 设置侦听
        for(StuDataWithButton stuDataWithButton : table.getItems()){
            stuDataWithButton.getDel().setText("删除");
            stuDataWithButton.getDel().setOnAction(e -> {
                Alert alert = new Alert(Alert.AlertType.WARNING, "操作不可逆，确定？",
                        ButtonType.OK, ButtonType.CANCEL);
                Button ok = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
                ok.setOnAction(evt -> {
                    try {
                        boolean isSucc = adminUser.deleteStuDataById(stuDataWithButton.getS_id());
                        if(isSucc){
                            table.getItems().remove(stuDataWithButton);
                        }else {
                            throw new Exception();
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                        delFail.show();
                    } catch (Exception exception){
                        exception.printStackTrace();
                        otherFail.show();
                    }
                });
                alert.show();
            });
        }
    }

    @FXML
    void addClick(ActionEvent event) {
        String s_id = inputSid.getText(),
                sname = inputSname.getText(),
                sex = sexChoice.getValue(),
                major = inputMajor.getText();


        if(s_id.isEmpty() || sname.isEmpty() ||
                sex.isEmpty() || major.isEmpty()){
            emptyFail.show();
            return;
        }
        StuData stuData = new StuData(s_id, sname,
                sex, major);
//        System.out.println(stuData);
        try {
            adminUser.addStuData(stuData);
            addSucc.show();
        } catch (SQLException e) {
            addFail.show();
            e.printStackTrace();
        }finally {
            clearClick(event);
            getAllStuClick(event);
        }
    }

    @FXML
    void updateClick(ActionEvent event) {
        String s_id = inputSid.getText(),
                sname = inputSname.getText(),
                sex = sexChoice.getValue(),
                major = inputMajor.getText();


        if(s_id.isEmpty() || sname.isEmpty() ||
                sex.isEmpty() || major.isEmpty()){
            emptyFail.show();
            return;
        }
        StuData stuData = new StuData(s_id, sname,
                sex, major);
        try {
            boolean isSucc = adminUser.updateStuData(stuData);
            if(isSucc){
                updateSucc.show();
            }else{
                getFail.show();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            clearClick(event);
            getAllStuClick(event);
        }
    }

    @FXML
    void getAllStuClick(ActionEvent event) {
        List<StuData> allStuData;
        try {
            allStuData = adminUser.getAllStuData();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        loadTableContent(allStuData);
    }

    @FXML
    void getStuClick(ActionEvent event) {
        if(inputSid.getText().isEmpty()){
            emptyFail.show();
            return;
        }
        try {
            StuData stuData = adminUser.getStuDataById(inputSid.getText());
            inputSname.setText(stuData.getSname());
            inputMajor.setText(stuData.getMajor());
            sexChoice.setValue(stuData.getSex());
        } catch (SQLException e) {
            getFail.show();
            e.printStackTrace();
        }
    }



    @FXML
    void searchClick(ActionEvent event) {
        if(inputSearch.getText().isEmpty()){
            seachWarn.show();
            return;
        }
        List<StuData> allStuData;
        try {
            allStuData = adminUser.searchStuData(inputSearch.getText());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        loadTableContent(allStuData);
    }

    @FXML
    void fuzzysearchClick(ActionEvent event) {
        if(inputSearch.getText().isEmpty()){
            seachWarn.show();
            return;
        }
        List<StuData> allStuData;
        try {
            allStuData = adminUser.searchStuDataFuzzy(inputSearch.getText());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        loadTableContent(allStuData);
    }

    @FXML
    public void clearClick(ActionEvent event) {
        inputSid.setText("");
        inputSname.setText("");
        inputMajor.setText("");
    }
    Alert delFail, otherFail, emptyFail, addFail, addSucc, getFail, updateSucc, seachWarn;
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        if(CurrentUser.USER instanceof AdminUser){
            adminUser = (AdminUser) CurrentUser.USER;
        }else{
            throw new RuntimeException();
        }
        // 绑定列
        s_id.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, String>("s_id"));
        sname.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, String>("sname"));
        sex.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, String>("sex"));
        major.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, String>("major"));
        bedName.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, String>("bedName"));
        buttonCol.setCellValueFactory(new PropertyValueFactory<StuDataWithButton, Button>("del"));
//        ObservableList<StuDataWithButton> testlist = FXCollections.observableArrayList();
//        testlist.addAll(new StuDataWithButton("1001", "xm", "M", "计算机专业","001"));
//        table.setItems(testlist);

        sexChoice.setItems(FXCollections.observableArrayList("M", "F"));
        sexChoice.setValue("M");

        delFail = new Alert(Alert.AlertType.ERROR, "无法删除，请联系DBA", ButtonType.CLOSE);
        otherFail = new Alert(Alert.AlertType.ERROR, "其他错误，请刷新重试", ButtonType.CLOSE);
        emptyFail = new Alert(Alert.AlertType.WARNING, "学生属性不能为空", ButtonType.OK);
        addFail = new Alert(Alert.AlertType.ERROR, "学号不能重复", ButtonType.CLOSE);
        addSucc = new Alert(Alert.AlertType.INFORMATION, "添加成功！", ButtonType.OK);
        getFail = new Alert(Alert.AlertType.WARNING, "查无此人", ButtonType.OK);
        updateSucc = new Alert(Alert.AlertType.INFORMATION, "修改成功！", ButtonType.OK);
        seachWarn = new Alert(Alert.AlertType.WARNING, "关键字不能为空", ButtonType.OK);
    }


}
